package com.wisenet.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

public class ServletUploadUtil {
	public static Logger logger = Logger.getLogger(ServletUploadUtil.class);
	
	// 文件允许格式
	private static final String[] ALLOW_FILES = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };

	/**
	 * 获取上传文件
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getFile(HttpServletRequest request) throws IOException {
		Map<String, Object> fileMap = null;
		logger.info("getRequestURI = " + request.getRequestURI());
		try {
			// 创建一个DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding("UTF-8");
			
			// 得到 FileItem 的集合 items
			List<FileItem> items = upload.parseRequest(request);
			if(items == null || items.size() == 0) {
				logger.info("items == null || items.size() == 0");
				return null;
			}
			
			fileMap = new HashMap<>();
			
			// 遍历 items
			for (FileItem item : items) {
				String name = item.getFieldName();
				if (!item.isFormField()) {
					// 判断是否非法类型
					if(FileTypeJudge.getType(item.getInputStream()) == null) {
						logger.info("上传非法文件: " + item.getName());
						return null;
					}
					fileMap.put("bytes", item.get());
				} else {
					fileMap.put(name, item.getString("UTF-8"));
				}
			}
			return fileMap;
		} catch (Exception e) {
			logger.info("上传出错：" + e.getMessage());
			if(fileMap != null) {
				logger.info("uid = " + fileMap.get("uid"));
			}
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取图片字节
	 * @param item
	 * @return
	 */
	public static byte[] getFileByte(FileItem item) {
		InputStream input = null;
		ByteArrayOutputStream outputStream = null;
		try {
			outputStream = new ByteArrayOutputStream();
			input = item.getInputStream();
			byte[] buff = new byte[1024];
			int rc;
			while ((rc = input.read(buff)) > 0) {
				outputStream.write(buff, 0, rc);
			}
			return outputStream.toByteArray();
		} catch (Exception e) {
			logger.error("获取图片流异常: " + e.getMessage());
		} finally {
			try {
				if (outputStream != null) outputStream.close();
				if (input != null) input.close();
			} catch (IOException e) {
				logger.info("关闭流异常: " + e.getMessage());
			}
		}
		return null;
	}
	
	/**
	 * 文件类型判断
	 * @param fileName
	 * @return
	 */
	public static boolean checkFileType(String fileName) {
		Iterator<String> type = Arrays.asList(ALLOW_FILES).iterator();
		while (type.hasNext()) {
			String ext = type.next();
			if (fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}
	
}
